function queryParams(params) {
	$('#theform').serializeArray().forEach(function fn(v){
		params[v.name] = v.value;
	});
    return params;
}

function responseHandler(root) {
	$('#theader').html('表格 记录数:'+root.hits.total+', 搜索耗时:'+root.took+'ms, 分片:'+root._shards.successful +'/'+ root._shards.total);
	
	return redrawByDayUnit(root);
}

function redrawByDayUnit(root){
	var aggField = '';
	
	aggField = 'terminal_os2';
	
	var r = [];
	root.aggregations['group_by@' + aggField + '@' + aggField].buckets.forEach(function (v){
		r.push({
			Name: v.key,
			pv: v['sum@' + aggField + '@pv'].value
		});
	});
	
	v = root.aggregations["group_by@site_id@site_id"].buckets[0];
	var summaryrow = {};
	if (v === undefined){
		summaryrow = {
			pv: '-'
		}
		
	} else {
		summaryrow = {
			'pv': v['sum@site_id@pv'].value
		}
	}
	
	$('#summarytable').bootstrapTable('updateRow', { index: 0, row:summaryrow });
	
	redrawChart(root.aggregations['group_by@terminal_os@terminal_os'].buckets);
	
	return r;
}

function redrawChart(currentData){
	
	var	indexName = '浏览量（PV）';
	
	var legend = [];
	var data1 = [];
	currentData.forEach(function(v){
		legend.push(v.key);
		data1.push({
			name:v.key,
			value:v['sum@terminal_os@pv'].value
		})
	});
	
	console.log(legend);
	console.log(data1);
	
	option = {
	    title : {
	        text: indexName,
	        x:'center'
	    },
	    tooltip : {
	        trigger: 'item',
	        formatter: "{a} <br/>{b} : {c} ({d}%)"
	    },
	    legend: {
	        orient: 'vertical',
	        left: 'left',
	        data: legend
	    },
	    series : [
	        {
	        	name: '访问次数',
	            type: 'pie',
	            radius : '55%',
	            center: ['50%', '60%'],
	            data: data1,
	            itemStyle: {
	                emphasis: {
	                    shadowBlur: 10,
	                    shadowOffsetX: 0,
	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
	                }
	            }
	        }
	    ]
	};
	var myChart = echarts.init(document.getElementById('main'));
	myChart.setOption(option, true);
}


function initTable(){
	
	$('#thetable').bootstrapTable('destroy');
	$('#thetable').bootstrapTable({
		showExport: true,
		url: '/analytics/equ.json',
		method: 'post',
		queryParams: queryParams,
		responseHandler: responseHandler,
		idField: 'Name',
		dataShowExport: true,
		sortStable: true,
		pagination: true,
		showPaginationSwitch: true,
		search: true,
		columns: [
			{
		        field: 'Name',
		        sortable: true,
		        title: '类型'
		    }, {
		        field: 'pv',
		        title: '浏览量（PV）',
		        sortable: true,
		        formatter: numt
		    }
		]
	});
	
}

function switchTable(){
	initTable();
}

$(document).ready(function () {

	$('#theform_commit').click(function (){
		switchTable();
	});
	
	switchTable();
	initDateRangePick($('#TimeDay'));
	
	$('#summarytable').bootstrapTable({
		data: [{
			pv: '-'
		}]
	});
	
	$.ajax({
		url: '/analytics/branch.json', 
		type: 'POST', 
		data:{ type:'site' }, 
		dataType: 'json', 
		error: function(){
			alert('Error loading branch');
		}, 
		success: function(root){
			var control = $('#BranchId')
			control.find('option').remove().end();
			control.append('<option value="">全部</option>');
			var kv = {}
			root.aggregations['group_by@branch_id@branch_id'].buckets.forEach(function (v){
				if (v.key.length == 0) return;
				if (b2b_map !== undefined && b2b_map[v.key] !== undefined){
					kv[v.key] = b2b_map[v.key] + " ( pv:" + v['sum@branch_id@pv'].value + " )";
				} else {
		        	kv[v.key] = v.key + " ( pv:" + v['sum@branch_id@pv'].value + " )";
		        }
			});
			$.each(kv, function (k,v){	
				control.append($('<option>', { value : k, text: v }));
			});
		} 
	}); 
	
});
